package com.zui.util;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;


/**
 * {"groupOp":"AND","rules":[{"field":"catalogName","op":"bw","data":"2"},
 * {"field":"parentCatalog.catalogName","op":"bw","data":"1"}]}
 * 
 * @author Sam
 * @since 1.0
 */
public class JQGridFilter implements Serializable{
	private static final long serialVersionUID = 1L;
	
	private String groupOp;
	private List<JQGridFilterRule> rules;
	
	public void addRule(JQGridFilterRule rule) {
		if (rules == null)
			rules = new ArrayList<JQGridFilterRule>();
		rules.add(rule);
	}
	
	@Override
	public String toString() {
		if (groupOp == null || rules == null)
			return null;
		
		StringBuffer sb = new StringBuffer();
		sb.append("{\"groupOp\":\"");
		sb.append(groupOp);
		sb.append("\",\"rules\":[");
		
		Iterator<JQGridFilterRule> it = rules.iterator();
		while (it.hasNext()) {
			JQGridFilterRule rule = it.next();
			sb.append("{\"field\":\"");
			if(rule.isAssociation()) {
				StringBuffer tempField = new StringBuffer();
				for(String hie:rule.getHierarchyFields()){
					tempField.append(hie);
					tempField.append(".");
				}
				tempField.append(rule.getField());
				sb.append(tempField);
			} else
				sb.append(rule.getField());
			sb.append("\",\"op\":\"");
			sb.append(rule.getOp());
			sb.append("\",\"data\":\"");
			sb.append(rule.getData());
			sb.append("\"},");
		}
		sb.deleteCharAt(sb.length()-1);
		sb.append("]}");
		return sb.toString();
	}

	
	public String getGroupOp() {
		return groupOp;
	}
	public void setGroupOp(String groupOp) {
		this.groupOp = groupOp;
	}
	public List<JQGridFilterRule> getRules() {
		return rules;
	}
	public void setRules(List<JQGridFilterRule> rules) {
		this.rules = rules;
	}


	
	
}